#!/bin/bash
export LANG=en_US.UTF-8
Where="/usr/bin/whereis"

AbsPath=$(dirname $0)
if [[ "$AbsPath" =~ ^[.] || "$AbsPath" =~ [^/] ]];then
    cd $AbsPath
    AbsPath="`pwd`"
fi

FPid=$(cat $AbsPath/*.pid 2>/dev/null)
Process="`echo $AbsPath |awk -F/ '{print $(NF-1)}'`"
ErrStopMesg1="\e[35m$Process 和 Pid 不匹配\e[0m"
ErrStopMesg2="\e[31m$Process 停止失败\e[0m"
ErrStopMesg3="\e[31m$Process 不存在\e[0m"

Errcode=1
OKcode=0

function STOPP(){
    kill -15 $1 2>/dev/null
    if [ "$?" = "0" ];then
        usleep 2000000
        rm -f $AbsPath/*.pid
        echo "Usage $0: $Process has been stoped."
    else
        echo -e $ErrStopMesg2
        exit $Errcode
    fi
}

# judge whereis and which
if ! [ "`$Where which 2>/dev/null`" ];then
    echo -e $ErrorderMesg1
    exit $Errcode
fi

# judge jps
if ! [ "`$Which jps 2>/dev/null`" ];then
    echo -e $ErrorderMesg2
    exit $Errcode
fi

# judge process and exec stop
Pid=`jps |grep -E $Process'\.' |awk '{print $1}'`
if [ -z "$FPid" -a -z "$Pid" ];then
    echo -e $ErrStopMesg3
    exit $Errcode
else
    if [ "$Pid" != "$FPid" ];then
        echo -e $ErrStopMesg1
        STOPP $Pid
    else
        STOPP $FPid
    fi
fi